<?php

class ErrorHandler extends Model{

	public function _construct() {
	}

	public function init() {
		set_error_handler(array($this,'error_handler'));
		$this->createDebugLogFile();
		//$this->errorLogExists();
	}
	
	private function createDebugLogFile() {
		if(file_exists(DEBUG_FILE_PATH) == false) {
			$created = fopen(DEBUG_FILE_PATH, 'w');	
		}		
	}
	
	public function error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
		$str = '';
	
		$dateStr = date('y.m.d-H:i');
		switch( $errno) {
			case E_ERROR;
				$str = "[".$dateStr."]Error: in file : ". $errfile." at line : ". $errline." ".$errstr;
				break;
			case E_WARNING;
				$str = "[".$dateStr."]Warning: in file : ". $errfile." at line : ". $errline." ".$errstr;
				break;
			case E_USER_NOTICE;
				break;
		}
		
		if(strlen($str) > 0) {
			$str .= "\n";
			$logFilePath = $this->getErrorLogFilePath();
			$logExists = $this->errorLogExists();
			if($logExists == false) {
				$logExists = $this->createErrorLogFile();
			}

			if($logExists == true && is_writable($logFilePath)) {
				file_put_contents($logFilePath, $str, FILE_APPEND);	
			}
		}
	}

	private function getErrorLogFilePath() {
		$dateStr = date("y_m_d");
		$logPath = LOG_FILE_PATH;
		$logParts = explode('.',$logPath);
		$logParts[count($logParts)-2] .= $dateStr;
		return implode('.',$logParts);		
	}
	
	private function errorLogExists() {
		$logNameWithDate = $this->getErrorLogFilePath();
		if(file_exists($logNameWithDate)) {
			return true;
		} 
		return false;
	}
	
	private function createErrorLogFile() {
		$logNameWithDate = $this->getErrorLogFilePath();

		if(file_exists($logNameWithDate) == false) {
			$created = fopen($logNameWithDate, 'w');
			if($created == false) {
				return false;
			}
		}
		return true;
	}	
}
?>